package cn.example.practice.db;

import cn.example.practice.util.JDBCUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DatabaseInitializer {
    private static final Logger LOGGER = Logger.getLogger(DatabaseInitializer.class.getName());

    public static void main(String[] args) {
        try {
            String sqlScript = new String(Files.readAllBytes(
                    Paths.get("src/cn/example/practice/db/recreate_tables.sql")));

            try (Connection conn = JDBCUtils.getConnection();
                 Statement stmt = conn.createStatement()) {

                // Split the script into individual statements
                String[] statements = sqlScript.split(";");

                // Execute each statement
                for (String statement : statements) {
                    String trimmed = statement.trim();
                    if (!trimmed.isEmpty()) {
                        stmt.execute(trimmed);
                    }
                }

                LOGGER.info("Database tables recreated successfully");
            }
        } catch (IOException | SQLException e) {
            LOGGER.log(Level.SEVERE, "Error initializing database", e);
        }
    }
}
